// pages/course/detail/detail.js
import {CourseModel} from '../../../model/course'
import { config } from '../../../config'
import {OrderModel} from '../../../model/order'
var order = new OrderModel()
var course = new CourseModel()
const manager = wx.getBackgroundAudioManager()
var app=getApp(); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bottom:0,
    id:0,
    detail:{},
    chapterList:[],
    isPlay:true,
    playStatus:true,
    progress:0,
    progressText:0,
    duration:0,
    durationText:0,
    navbarActiveIndex: 0,
    navbarTitle: [
      "介绍",
      "目录",
    ],
    showActionsheet: false,
    groups: [
        { text: '发送给朋友', value: 1 },
        { text: '生成海报', value: 2 },
    ],
    system:config.system
  },
  close: function () {
    this.setData({
        showActionsheet: false
    })
},
  btnClick(e) {
    console.log(e)
    switch(e.detail.value){
      case 1:
        console.log(e.detail.value)
        break;
      case 2:
        this.selectComponent("#poster").formSubmit()
        break;
    }
    this.close()
},
  onNavBarTap: function (event) {
    // 获取点击的navbar的index
    let navbarTapIndex = event.currentTarget.dataset.navbarIndex
    // 设置data属性中的navbarActiveIndex为当前点击的navbar
    this.setData({
      navbarActiveIndex: navbarTapIndex
    })
    if(this.data.navbarActiveIndex===1){
      this.chapterList()
    }
  },
  selectChapter:function(e){
    var data = e.currentTarget.dataset
    console.log(data.id);
    course.courseDetailSelectById(data.id).then(
      res=>{
        if(res.code === 0){
          this.setData({
          detail:res.data,
          isPlay:true
        })
        if(res.data.mediaType === 1){
          if(res.data.nicePrice===0 || res.data.isBuy===1 ||res.data.isAudition === 1){
            manager.title = res.data.title
            manager.epname = res.data.title
            manager.singer = res.data.realName
            manager.coverImgUrl = res.data.cover
            manager.src = res.data.mediaUrl
            this.playMusic();
              }else{
                wx.showToast({
                  title: '请先订阅课程',
                  icon:'none'
                })
              }
            }}
            else{
              wx.showToast({
                title: res.msg,
                icon:'none'
              })
            }
      }
    )
  },
  detail(){
    course.detail(this.data.id).then(
      res=>{
        if(res.code === 0 ){
          this.setData({
            detail:res.data
          })
          if(config.isMobile ==="1"){
            if(res.data.mediaType === 1){
              if(res.data.nicePrice===0 || res.data.isBuy===1 ||res.data.isAudition === 1){
                manager.title = res.data.title
                manager.epname = res.data.title
                manager.singer = res.data.realName
                manager.coverImgUrl = res.data.cover
                manager.src = res.data.mediaUrl
                this.playMusic();
                  }else{
                    wx.showToast({
                      title: '请先订阅课程',
                      icon:'none'
                    })
                  }
             }
          }else{
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
          
        }else{
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
      }
    )
  },
  chapterList(){
    course.chapter(this.data.id).then(
      res=>{
        if(res.code === 0 ){
          this.setData({
            chapterList:res.data.list||[],
          })
        }else{
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
      }
    )
  },
  payAction:function(e){
    var that = this
    if(this.data.detail.isBuy===1 || this.data.detail.nicePrice===0){
      return
    }else if(config.system ==='ios'){
      wx.showToast({
        title: '由于相关规范，IOS功能暂不可用',
        icon:'none'
      })
    }else{
      order.course(this.data.detail.id).then(
        res=>{
          console.log(res)
          if (res.code===0) {
            that.pay(res.data)
          }
        }
      )
    }
    console.log(e)
  },

  shareAction:function(e){
    this.setData({
      showActionsheet: true
  })
  },

  //
  //音频播放
 
playMusic: function () {
  let that = this;
  manager.currentTime = 0;
   
  manager.onPlay(function () {   
  that.setData({
   
  playStatus: true
   
  })
   
  that.countTimeDown(that, manager);
   
  });
   
  manager.onPause(function () {
   
  that.setData({
   
  playStatus: false
   
  }) 
  });
   
  manager.onEnded(function () {
      
  that.setData({
   
  playStatus: false
   
  })
  });
   
  },
  //循环计时
 
countTimeDown: function (that, manager, cancel) {
  if (that.data.playStatus) {
   
  setTimeout(function () {
   
  if (that.data.playStatus) {
   
  // console.log("duration: " + manager.duration);
   
  that.setData({
   
  progress: Math.ceil(manager.currentTime),
   
  progressText: that.formatTime(Math.ceil(manager.currentTime)),
   
  duration: Math.ceil(manager.duration),
   
  durationText: that.formatTime(Math.ceil(manager.duration))
   
  })
   
  that.countTimeDown(that, manager);
   
  }
  }, 1000)
   
  } 
  },
  
//拖动事件
 
sliderChange: function (e) {
 
  let manager = wx.getBackgroundAudioManager();
   
  manager.pause();
   
  manager.seek(e.detail.value);
   
  this.setData({
   
  progressText: this.formatTime(e.detail.value)
   
  })
   
  setTimeout(function () {
   
  manager.play();
   
  }, 1000);
   
  },
  
  play: function () {
    if(this.data.playStatus){
      manager.pause()
    this.setData({
      playStatus : false
    })
  }else{
    manager.play()
    this.setData({
      playStatus : true
    })
  }
  },
  pay(orderId){
    order.pay(orderId).then(
      res=>{
        if (res.code===0) {
          if (res.data===null) {
            this.detail()
            return
          }
          console.log(res.data)
          var data = JSON.parse(res.data);
          console.log(data)
          console.log(data.timeStamp)
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: 'MD5',
            paySign: data.paySign,
            success (resp) {
              console.log(resp)
              wx.showToast({
                title: '支付成功',
                icon: 'none'
              })
              this.detail()
             },
             fail(resp){
              console.log(resp)
             }
          })
        }
      }
    )
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)    
    this.setData({
      bottom:config.statusBarHeight,
      id:options.id,
    })
    wx.showShareMenu({
      withShareTicket:true,
      menus:['shareAppMessage','shareTimeline']
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (e) {

    },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.detail()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let url = encodeURIComponent('/pages/course/detail/detail?id='+this.data.id);
    return {
      title: this.data.detail.title,
      path: `/pages/course/list/list?url=${url}&id=${app.globalData.userInfo.id}`
    }
  },
  onShareTimeline(){
    
  },
  formatTime: function (s) {
 
    let t = '';
     
    s = Math.floor(s);
     
    if (s > -1) {
     
    let min = Math.floor(s / 60) % 60;
     
    let sec = s % 60;
     
    if (min < 10) {
     
    t += "0";
     
    }
     
    t += min + ":";
     
    if (sec < 10) {
     
    t += "0";
     
    }
     
    t += sec;
     
    }
     
    return t;
     
    },
})